package com.bruip.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bruip.reggie.common.BaseResponse;
import com.bruip.reggie.common.Constant;
import com.bruip.reggie.pojo.Employee;
import com.bruip.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

/**
 * @author 王若龙
 * @date 2022-10-04 22:50
 */
@RestController
@Slf4j
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 登录接口
     *
     * @param employee 员工
     * @param request  请求
     * @return {@link BaseResponse}<{@link Employee}>
     */
    @PostMapping("/login")
    public BaseResponse<Employee> login(@RequestBody Employee employee, HttpServletRequest request) {
        String username = employee.getUsername();
        String password = employee.getPassword();
        if (!StringUtils.isEmpty(username) && StringUtils.isEmpty(password)) {
            return BaseResponse.error("用户名或密码不能为空");
        }
        //密码加密
        password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));

        //查询结果
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, username);
        Employee emp = employeeService.getOne(queryWrapper);
        //用户名校验
        if (emp == null) {
            return BaseResponse.error("用户名或密码错误");
        }
        //密码校验
        if (!password.equals(emp.getPassword())) {
            return BaseResponse.error("用户名或密码错误");
        }
        //用户状态校验
        if (emp.getStatus() == 0) {
            return BaseResponse.error("账户被锁定");
        }

        //校验通过，将员工id存入session,返回员工信息
        request.getSession().setAttribute("employee", emp.getId());
        return BaseResponse.success(emp);
    }

    /**
     * 注销接口
     * constant
     *
     * @param request 请求
     * @return {@link BaseResponse}<{@link String}>
     */
    @PostMapping("/logout")
    public BaseResponse<String> logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return BaseResponse.success("logout success");
    }

    /**
     * 添加员工
     *
     * @param employee 员工
     * @return {@link BaseResponse}<{@link String}>
     */
    @PostMapping
    public BaseResponse<String> addEmployee(@RequestBody Employee employee, HttpServletRequest request) {
        log.info("添加员工，员工信息：{}", employee.toString());

        employee.setPassword(Constant.DEFAULT_PASSWORD);
        /*Long empId = (Long) request.getSession().getAttribute("employee");
        employee.setCreateTime(LocalDateTime.now());
        employee.setCreateUser(empId);
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(empId);*/

        boolean save = employeeService.save(employee);
        return BaseResponse.success("添加成功");
    }

    /**
     * 员工信息页面
     *
     * @param page     页面
     * @param pageSize 页面大小
     * @param name     名字
     * @return {@link BaseResponse}<{@link Page}>
     */
    @GetMapping("/page")
    public BaseResponse<Page> employeeInfoPage(int page, int pageSize, String name) {
        log.info("员工管理页查询, page = {}, pageSize = {}, name = {}", page, pageSize, name);

        //构造分页构造器
        Page pageInfo = new Page(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        //添加排序条件
        queryWrapper.orderByDesc(Employee::getCreateTime);
        //查询
        employeeService.page(pageInfo, queryWrapper);

        return BaseResponse.success(pageInfo);
    }

    /**
     * 修改员工信息
     *
     * @param employee 员工
     * @param request  请求
     * @return {@link BaseResponse}<{@link String}>
     */
    @PutMapping
    public BaseResponse<String> setStatus(@RequestBody Employee employee, HttpServletRequest request) {
        log.info("修改用户：{}", employee.toString());
        Long empId = (Long) request.getSession().getAttribute("employee");
        //设置修改用户的权限
        if (empId != 1L && !empId.equals(employee.getId())) {
            return BaseResponse.error("当前用户没有权限");
        }
        /* employee.setUpdateUser(empId);
        employee.setUpdateTime(LocalDateTime.now());*/

        employeeService.updateById(employee);
        return BaseResponse.success("修改成功");
    }

    /**
     * 根据id查询员工信息
     *
     * @param id id
     * @return {@link BaseResponse}<{@link Employee}>
     */
    @GetMapping("/{id}")
    public BaseResponse<Employee> updateEmployee(@PathVariable("id") Long id) {
        log.info("通过id查询用户信息： {}", id);
        Employee e = employeeService.getById(id);
        if (e != null) {
            return BaseResponse.success(e);
        }
        return BaseResponse.error("更新失败");
    }
}
